import { Toast } from "antd-mobile";
import { takeEvery } from "redux-saga/effects";
import { NATIVE_CLASS } from "@common/constants";
import { callNativeFunc } from "@common/saga-helper";
import {
  SAGA_DATA_SYNC_CLEAR,
  SAGA_DATA_SYNC_DOWNLOAD,
  SAGA_DATA_SYNC_LOAD_ITEMS,
} from "./saga-types";
import { SET_DATA_SYNC_ITEMS } from "./action-types";

function* loadDataSyncItemsSaga() {
  yield takeEvery(SAGA_DATA_SYNC_LOAD_ITEMS, function* (_action) {
    yield* callNativeFunc({
      effects: [
        {
          payload: {
            classFullName: NATIVE_CLASS.DataSyncHandler,
            action: "loadItems",
            needNonce: false,
          },
          respActions: [SET_DATA_SYNC_ITEMS],
        },
      ],
    });
  });
}

function* downloadDataSaga() {
  yield takeEvery(SAGA_DATA_SYNC_DOWNLOAD, function* (action) {
    yield* callNativeFunc({
      effects: [
        {
          payload: {
            classFullName: NATIVE_CLASS.DataSyncHandler,
            action: "downloadByCodes",
            params: action.payload,
            needNonce: true,
          },
          callback: () =>
            Toast.show({
              icon: "success",
              content: "同步完毕",
              maskClickable: false,
            }),
        },
        {
          payload: {
            classFullName: NATIVE_CLASS.DataSyncHandler,
            action: "loadItems",
            needNonce: false,
          },
          respActions: [SET_DATA_SYNC_ITEMS],
        },
      ],
    });
  });
}

function* clearSyncDataSaga() {
  yield takeEvery(SAGA_DATA_SYNC_CLEAR, function* (action) {
    yield* callNativeFunc({
      effects: [
        {
          payload: {
            classFullName: NATIVE_CLASS.DataSyncHandler,
            action: "clearByCodes",
            params: action.payload,
            needNonce: false,
          },
          callback: () =>
            Toast.show({
              icon: "success",
              content: "清理完毕",
              maskClickable: false,
            }),
        },
        {
          payload: {
            classFullName: NATIVE_CLASS.DataSyncHandler,
            action: "loadItems",
            needNonce: false,
          },
          respActions: [SET_DATA_SYNC_ITEMS],
        },
      ],
    });
  });
}

export default [
  loadDataSyncItemsSaga(),
  downloadDataSaga(),
  clearSyncDataSaga(),
];
